package com.exampl.health.interceptor;

import com.exampl.health.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        // 获取请求的URL
        String url = request.getRequestURI();

        // 公开地址（无需登录即可访问）
        if (url.indexOf("/login") >= 0 || url.indexOf("/register") >= 0 ||
                url.indexOf("/static/") >= 0) {
            return true;
        }

        // 获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        // 判断session中是否有用户数据
        if (user != null) {
            // 用户已登录，放行
            return true;
        }

        // 判断请求是否为AJAX请求
        if (request.getHeader("x-requested-with") != null &&
                request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            // 如果是AJAX请求，返回JSON格式的错误信息
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"success\":false,\"message\":\"请先登录\"}");
        } else {
            // 如果是普通请求，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }

        return false;
    }
}
